package com.gec.service.Impl;

import com.gec.dao.RoleDao;
import com.gec.domain.PageBean;
import com.gec.domain.PageParam;
import com.gec.domain.Role;
import com.gec.service.abst.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/*
 *  Type: Class
 *  Author: DawnFz.com
 *  Date: 2022/10/25 13:03
 *  Project: HotelSSM
 *  Version: 1.0
 *  Describe: [RoleServiceImpl类]
 */
@Service
public class RoleServiceImpl extends BaseService implements RoleService {
    private final RoleDao roleDao;

    public RoleServiceImpl(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    @Override
    public PageBean<Role> getRoleList(PageParam param) throws SQLException {
        Map<String, String> map = param.getKeywords();
        List<Role> list;

        PageBean<Role> pBean = new PageBean<>();

        int page = param.getPage();
        int size = param.getLimit();
        PageHelper.startPage(page, size, true);
        list = roleDao.getRoleList(map);
        PageInfo<Role> pageInfo = new PageInfo<>(list);

        int count = (int) pageInfo.getTotal();

        pBean.setCount(count);
        pBean.setData(list);
        return pBean;
    }

    @Override
    public Role getRoleById(String id) throws SQLException {
        Role role = roleDao.getRoleById(id);
        if (role == null) {
            throw new SQLException("角色不存在");
        }
        return role;
    }

    @Override
    public boolean saveRole(Role role) throws SQLException {
        return roleDao.updateRole(role) > 0;
    }

    @Override
    public boolean delRole(String id) throws SQLException {
        return roleDao.delRole(id) > 0;
    }

    @Override
    public boolean addRole(Role role) throws SQLException {
        String id = role.getId();
        Role rT = roleDao.getRoleById(id);
        if (rT != null) throw new SQLException("该角色Id已存在");
        return roleDao.addRole(role) > 0;
    }

    @Override
    public boolean addRolePermission(String roleId, String[] permission) throws SQLException {
        boolean f = true;
        for (String s : permission) {
            System.out.println("+---------------------------+");
            System.out.println(s);
            System.out.println("+---------------------------+");
            boolean b = roleDao.addRolePermission(uuid(), roleId, s);
            if (!b) {
                f = false;
            }
        }
        return f;
    }
}
